package com.longcai.piaojia.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.activity.ChooseCityActivity;
import com.longcai.piaojia.activity.DayDaySignActivity;
import com.longcai.piaojia.activity.GoodsInfoActivity;
import com.longcai.piaojia.activity.LoginActivity;
import com.longcai.piaojia.activity.MessageActivity;
import com.longcai.piaojia.activity.ProjectActivity;
import com.longcai.piaojia.activity.SearchActivity;
import com.longcai.piaojia.activity.ShowActivity;
import com.longcai.piaojia.activity.WebActivity;
import com.longcai.piaojia.adapter.HomeListAdapter;
import com.longcai.piaojia.adapter.IndexNumGridAdapter;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.HomeGet;
import com.longcai.piaojia.widget.NoScrollGridView;
import com.longcai.piaojia.widget.NoScrollListView;
import com.longcai.piaojia.widget.UPMarqueeView;
import com.longcai.piaojia.widget.ViewHomeAdvert;
import com.longcai.piaojia.widget.photo.AlphaPageTransformer;
import com.longcai.piaojia.widget.photo.ScaleInTransformer;
import com.module.pull.ObservableScrollView;
import com.module.pull.PullToRefreshBase;
import com.module.pull.PullToRefreshLisScrollView;
import com.module.pull.ScrollViewListener;
import com.zcx.helper.app.AppCallBack;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.glide.GlideLoader;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.http.Http;
import com.zcx.helper.pager.Carousel;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilKeyBoard;
import com.zcx.helper.util.UtilMD5;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/8/2.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {//, AbsListView.OnScrollListener /*渐变效果监听*/

    //    @BoundView(R.id.fragment_home_rl) private RelativeLayout fragment_home_rl;
    @BoundView(R.id.home_choose_city_ll)
    private LinearLayout home_choose_city_ll;
    @BoundView(R.id.home_choose_city_tv)
    private TextView home_choose_city_tv;
    @BoundView(R.id.home_search_rl)
    private RelativeLayout home_search_rl;
    @BoundView(R.id.search_title_et)
    public EditText search_title_et;
    @BoundView(R.id.search_title_ll)
    private LinearLayout search_title_ll;
    @BoundView(R.id.search_title_clear_ll)
    private LinearLayout search_title_clear_ll;
    @BoundView(R.id.home_title_message_rl)
    private RelativeLayout home_title_message_rl;

    @BoundView(R.id.home_sv)
    private PullToRefreshLisScrollView pullToRefreshScrollView;

    /*渐变效果标题和背景*/
    @BoundView(R.id.home_ll)
    private LinearLayout home_ll;
//    @BoundView(R.id.title_name_tv) private TextView title_name_tv;

    @BoundView(R.id.home_list_lv)
    private NoScrollListView home_list_lv;

    private List<HomeGet.HomeGuessYouLikeEntity> guessyoulike_lists = new ArrayList<>();
    private List<HomeGet.HomeShowListEntity> show_lists = new ArrayList<>();

    private HomeListAdapter homeListAdapter;

    @BoundView(R.id.home_ad_rl)
    private RelativeLayout home_ad_rl;
    @BoundView(R.id.home_ad_vha)
    private ViewHomeAdvert home_ad_vha;

    //每日抽奖
//    @BoundView(R.id.home_sign_in_ll) private LinearLayout home_sign_in_ll;
    //    @BoundView(R.id.home_nearby_ll) private LinearLayout home_nearby_ll;
//    @BoundView(R.id.home_integration_shop_ll) private LinearLayout home_integration_shop_ll;

    //活动
    //  @BoundView(R.id.home_dance_ballet_ll) private LinearLayout home_dance_ballet_ll;


    //儿童亲子
//    @BoundView(R.id.home_sport_ll) private LinearLayout home_sport_ll;

    //演唱会
  /*  @BoundView(R.id.home_child_ll)
    private LinearLayout home_child_ll;*/

    //惠民卡
//    @BoundView(R.id.home_music_drama_ll)
//    private LinearLayout home_music_drama_ll;

    //话剧舞台
   /* @BoundView(R.id.home_manga_ll)
    private LinearLayout home_manga_ll;*/

    @BoundView(R.id.home_child_tv)
    private TextView home_child_tv;
    @BoundView(R.id.home_show_tv)
    private TextView home_show_tv;
    @BoundView(R.id.home_drama_tv)
    private TextView home_drama_tv;
    @BoundView(R.id.home_coupon_tv)
    private TextView home_coupon_tv;

    @BoundView(R.id.home_child_iv)
    private ImageView home_child_iv;
    @BoundView(R.id.home_show_iv)
    private ImageView home_show_iv;
    @BoundView(R.id.home_drama_iv)
    private ImageView home_drama_iv;
    @BoundView(R.id.home_coupon_iv)
    private ImageView home_coupon_iv;

    @BoundView(R.id.home_ad_upmv)
    private UPMarqueeView home_ad_upmv;
//    @BoundView(R.id.home_ad_tv) private TextView home_ad_tv;

    @BoundView(R.id.home_more_detail_ll)
    private RelativeLayout home_more_detail_ll;
    @BoundView(R.id.home_center_ad_ll)
    private LinearLayout home_center_ad_ll;
    @BoundView(R.id.home_ad_center_rl)
    private RelativeLayout home_ad_center_rl;
    @BoundView(R.id.home_ad_center_icon_ll)
    private LinearLayout home_ad_center_icon_ll;
    @BoundView(R.id.home_ad_center_icon_iv)
    private ImageView home_ad_center_icon_iv;
    @BoundView(R.id.home_center_ad_tv)
    private TextView home_center_ad_tv;
    //每日抽奖送不停
    @BoundView(R.id.home_center_ad_iv)
    private ImageView home_center_ad_iv;
    @BoundView(R.id.home_recommend_ll)
    private LinearLayout home_recommend_ll;
    @BoundView(R.id.id_viewpager)
    private ViewPager id_viewpager;
    @BoundView(R.id.home_like_ll)
    private LinearLayout home_like_ll;
    @BoundView(R.id.home_container_viewpager)
    private FrameLayout home_container_viewpager;
    private List<HomeGet.HomeToplistEntity> toplists = new ArrayList<>();
    private List<View> views = new ArrayList<>();
    private PagerAdapter mAdapter;
    private HomeGet.HomeEntity home;
    private ObservableScrollView scrollView;

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");

//    private HomeGet.Windows windows = new HomeGet.Windows();


//    private int number =0;
//    private boolean isRunning=true;

    private String mCityId;

    private PopupWindow popWindow;


    private TextView etname, tv01, tv02, tv03;

    private IndexNumGridAdapter chooseGoodsNumGridAdapter;
    public List<HomeGet.HomeClassifyEntity> lists_num = new ArrayList<>();
    @BoundView(R.id.choose_goods_num_nsgv)
    private NoScrollGridView choose_goods_num_nsgv;


    Dialog dia;

    ImageView mClose_btn;

    ImageView btn_close2;
    public HomeGet homeGet = new HomeGet(new AsyCallBack<HomeGet.HomeEntity>() {

        @Override
        public void onEnd(String toast, int type) throws Exception {
            super.onEnd(toast, type);

            Http.getInstance().dismiss();

            pullToRefreshScrollView.onPullDownRefreshComplete();
            pullToRefreshScrollView.onPullUpRefreshComplete();
            setLastUpdateTime();


        }

        @Override
        public void onSuccess(String toast, int type, final HomeGet.HomeEntity homeEntity) throws Exception {
            super.onSuccess(toast, type, homeEntity);

            home = homeEntity;

            BaseApplication.BasePreferences.saveCustomServiceTel(homeEntity.services_tel);

            if (homeEntity.banner.size() > 1) {

                home_ad_vha.setIsShow(true);

            }

//            windows = homeEntity.window;






/*            String str_url=home.window.get(0).picurl;

            Log.d(str_url,"66666666666666666");*/


          /*  Log.d(homeEntity.window.picurl, "66666666666666666");
            GlideLoader.getInstance().get(getActivity(), homeEntity.window.picurl, mClose_btn, R.mipmap.home_center);

*/
            home_ad_vha.setItemList(homeEntity.banner);

            home_ad_vha.setOnCarouselItemListener(new Carousel.OnCarouselItemListener<HomeGet.HomeBannerEntity>() {

                @Override
                public void onCarouselItemClick(HomeGet.HomeBannerEntity banner) {

//                    UtilKeyBoard.closeKeybord(search_title_et, getActivity());

                    closeKeybord();

                    Bundle bundle;

                    switch (banner.type) {

                        case "1":
                            bundle = new Bundle();
                            bundle.putString("title", banner.title);
                            bundle.putString("url", Conn.SERVICE + Conn.INDEX_BANNER_WEB + "?id=" + banner.id);

//                    Log.e("这是banner web地址", Conn.SERVICE + Conn.INDEX_BANNER_WEB + "?id=" + banner.id);

                            startActivity(new Intent(getActivity(), WebActivity.class).putExtras(bundle));

                            break;

                        case "2":

                            startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("id", banner.good_id).putExtra("region_id",mCityId));

                            break;

                        case "3":

                            bundle = new Bundle();

                            bundle.putString("title", banner.title);
                            bundle.putString("url", banner.url);

//                    Log.e("这是banner web地址", Conn.SERVICE + Conn.INDEX_BANNER_WEB + "?id=" + banner.id);

                            startActivity(new Intent(getActivity(), WebActivity.class).putExtras(bundle));

                            break;

                    }


                }

            });

            if (homeEntity.classify.size() > 0) {

                lists_num.clear();
                lists_num.addAll(homeEntity.classify);
                // lists_num=homeEntity.classify;
                chooseGoodsNumGridAdapter = new IndexNumGridAdapter(getActivity(), lists_num);
                choose_goods_num_nsgv.setAdapter(chooseGoodsNumGridAdapter);


                choose_goods_num_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
                choose_goods_num_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));


                choose_goods_num_nsgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (TextUtils.isEmpty(BaseApplication.BasePreferences.readUserId())) {
                            startActivity(new Intent(getActivity(), LoginActivity.class));
                        } else if (home.classify.get(position).id.equals("8")) {

                           /* String userid = BaseApplication.BasePreferences.readUserId();
                            //  String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");
                            String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");

                            Bundle bundle1 = new Bundle();

                            bundle1.putString("url", Conn.BASE_URL + Conn.WEB_DIAL_INDEX + "?user_id=" + userid + "&token=" + token);


                            startActivity(new Intent(getActivity(), DayDaySignActivity.class).putExtras(bundle1));*/

                            String userid = BaseApplication.BasePreferences.readUserId();
                            //  String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");
                            String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");

                            Bundle bundle1 = new Bundle();

                            bundle1.putString("url", Conn.BASE_URL + Conn.WEB_DIAL_INDEX + "?user_id=" + userid + "&token=" + token);


                            startActivity(new Intent(getActivity(), DayDaySignActivity.class).putExtras(bundle1));
                        } else if (home.classify.get(position).id.equals("9")) {
                            startActivity(new Intent(getActivity(), ProjectActivity.class));
                        } else {
                            Bundle bundle_child = new Bundle();
                            bundle_child.putString("title", home.classify.get(position).title);
                            bundle_child.putString("id", home.classify.get(position).id);

                            startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_child));

                        }


                       /* if (position == 0) {
                            Bundle bundle_child = new Bundle();
                            bundle_child.putString("title", home.classify.get(0).title);
                            bundle_child.putString("id", home.classify.get(0).id);

                            startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_child));


                        } else if (position == 1) {

                            Bundle bundle_show = new Bundle();
                            bundle_show.putString("title", home.classify.get(1).title);
                            bundle_show.putString("id", home.classify.get(1).id);

                            startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_show));
                        } else if (position == 2) {

                            Bundle bundle_coupon = new Bundle();
                            bundle_coupon.putString("title", home.classify.get(2).title);
                            bundle_coupon.putString("id", home.classify.get(2).id);

                            startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_coupon));


                        } else if (position == 3) {
                            Bundle bundle_show = new Bundle();
                            bundle_show.putString("title", home.classify.get(3).title);
                            bundle_show.putString("id", home.classify.get(3).id);

                            startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_show));

                        }

                        else if (homeEntity.classify.get(position).id.equals("9")) {

                            startActivity(new Intent(getActivity(), ProjectActivity.class));

                        } else if (homeEntity.classify.get(position).id.equals("8")) {
                     *//*   Bundle bundle_drama = new Bundle();
                        bundle_drama.putString("title", home.classify.get(3).title);
                        bundle_drama.putString("id", home.classify.get(3).id);

                        startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_drama));
*//*
                            //startActivity(new Intent(getActivity(), SignInActivity.class));

                            if (!BaseApplication.BasePreferences.readIsLogin()) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                            } else {

                                String userid = BaseApplication.BasePreferences.readUserId();
                                //  String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");
                                String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");

                                Bundle bundle1 = new Bundle();

                                bundle1.putString("url", Conn.BASE_URL + Conn.WEB_DIAL_INDEX + "?user_id=" + userid + "&token=" + token);


                                startActivity(new Intent(getActivity(), DayDaySignActivity.class).putExtras(bundle1));
                            }


                        } else {

                        }
*/

                    }
                });

            }

            if (homeEntity.toplist.size() > 0) {

                toplists.addAll(homeEntity.toplist);
                home_more_detail_ll.setVisibility(View.VISIBLE);
                setView();
                home_ad_upmv.setViews(views);

            } else {

                home_more_detail_ll.setVisibility(View.GONE);

            }

//            getActivity().runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//
//                    while (isRunning){
//                        SystemClock.sleep(3000);
//                        home_ad_tv.next();
//                        number++;
//                        home_ad_tv.setText(homeEntity.toplist.get(number%homeEntity.toplist.size()).title);
//                    }
//
//                }
//            });

            if (homeEntity.advertisement.size() > 0) {

                home_center_ad_ll.setVisibility(View.VISIBLE);

                if (TextUtils.isEmpty(homeEntity.advertisement.get(0).icon) && TextUtils.isEmpty(homeEntity.advertisement.get(0).title)) {

                    home_ad_center_rl.setVisibility(View.GONE);

                } else {

                    home_ad_center_rl.setVisibility(View.VISIBLE);

                    if (TextUtils.isEmpty(homeEntity.advertisement.get(0).icon)) {

                        home_ad_center_icon_ll.setVisibility(View.GONE);

                    } else {

                        home_ad_center_icon_ll.setVisibility(View.VISIBLE);

                        GlideLoader.getInstance().get(getActivity(), homeEntity.advertisement.get(0).icon, home_ad_center_icon_iv, R.mipmap.ad_center_icon);

                    }

                    if (TextUtils.isEmpty(homeEntity.advertisement.get(0).title)) {

                        home_center_ad_tv.setVisibility(View.GONE);

                    } else {

                        home_center_ad_tv.setVisibility(View.VISIBLE);

                        home_center_ad_tv.setText(homeEntity.advertisement.get(0).title);

                    }

                }

                GlideLoader.getInstance().get(getActivity(), homeEntity.advertisement.get(0).picurl, home_center_ad_iv, R.mipmap.home_center);
                //GlideLoader.getInstance().get(getActivity(), homeEntity.window.picurl, home_center_ad_iv, R.mipmap.home_center);
            } else {

                home_center_ad_ll.setVisibility(View.GONE);

            }

            if (homeEntity.show_list.size() > 0) {

                home_recommend_ll.setVisibility(View.VISIBLE);
                show_lists.addAll(homeEntity.show_list);

                if (homeEntity.show_list.size() >= 3) {

                    id_viewpager.setCurrentItem(1);

                }

                mAdapter.notifyDataSetChanged();

            } else {

                home_recommend_ll.setVisibility(View.GONE);

            }

            if (homeEntity.GuessYouLike.size() > 0) {

                home_like_ll.setVisibility(View.VISIBLE);
                guessyoulike_lists.addAll(homeEntity.GuessYouLike);
                homeListAdapter.notifyDataSetChanged();

            } else {

                home_like_ll.setVisibility(View.GONE);

            }


        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            Toast.makeText(getActivity(), toast, Toast.LENGTH_LONG).show();

        }

    });

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = BoundViewHelper.boundView(this, inflater.inflate(R.layout.fragment_home, null));

        View view_head = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) inflater.inflate(R.layout.fragment_home_head, null)));

//        View view_bottom = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) inflater.inflate(R.layout.fragment_home_bottom, null)));

        home_choose_city_tv.setText(BaseApplication.BasePreferences.getCityName());

        HomeGet.HomeBannerEntity homeBannerEntity = new HomeGet.HomeBannerEntity();
        homeBannerEntity.good_id = "";
        homeBannerEntity.id = "";
        homeBannerEntity.picurl = "";
        homeBannerEntity.title = "";
        homeBannerEntity.type = "";

        List<HomeGet.HomeBannerEntity> list = new ArrayList<>();
        list.add(homeBannerEntity);

        HomeGet.Classify homeclassify = new HomeGet.Classify();


        home_ad_vha.setIsShow(false);

        home_ad_vha.setItemList(list);

        pullToRefreshScrollView.setPullLoadEnabled(false);
        pullToRefreshScrollView.setScrollLoadEnabled(false);
        pullToRefreshScrollView.setPullRefreshEnabled(true);

        scrollView = pullToRefreshScrollView.getRefreshableView();

        scrollView.setVerticalScrollBarEnabled(false);

        scrollView.addView(view_head);

        homeListAdapter = new HomeListAdapter(getActivity(), guessyoulike_lists);
        home_list_lv.setAdapter(homeListAdapter);


//        home_list_lv.addHeaderView(view_head);
//
//
//
//
//
//
// home_list_lv.addFooterView(view_bottom);

        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) home_ad_rl.getLayoutParams();
        layoutParams.height = width;
        home_ad_rl.setLayoutParams(layoutParams);








      /*  LinearLayout.LayoutParams layoutParams_ad_iv = (LinearLayout.LayoutParams) home_center_ad_iv.getLayoutParams();
        layoutParams_ad_iv.height = width / 2;
        home_center_ad_iv.setLayoutParams(layoutParams_ad_iv);*/

//        RelativeLayout.LayoutParams layoutParams_lv = (RelativeLayout.LayoutParams) home_list_lv.getLayoutParams();
//        layoutParams_lv.topMargin = (width * 5 / 9)-ScaleScreenHelperFactory.getInstance().getWidthHeight(40);
//        home_list_lv.setLayoutParams(layoutParams_lv);

        scrollView.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {

//                UtilKeyBoard.closeKeybord(search_title_et, getActivity());
                closeKeybord();

                if (y <= 0) {
                    home_ll.setBackgroundColor(Color.argb(0, 255, 255, 255));
                    home_search_rl.setBackgroundResource(R.drawable.home_search_et_bg);


                } else if (y > 0 && y <= ScaleScreenHelperFactory.getInstance().getWidthHeight(86)) {
                    float scale = (float) y / ScaleScreenHelperFactory.getInstance().getWidthHeight(86);
                    float alpha = (255 * scale);
                    home_ll.setBackgroundColor(Color.argb((int) alpha, 255, 102, 57));
//                    home_search_rl.setBackgroundResource(R.drawable.home_search_et_white_bg);

                } else {
                    home_ll.setBackgroundColor(Color.argb(255, 255, 102, 57));
                    home_search_rl.setBackgroundResource(R.drawable.home_search_et_white_bg);

                }


            }
        });

        home_list_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("id", guessyoulike_lists.get(position).id).putExtra("region_id",mCityId));

            }
        });

        /*渐变监听设置*/
//        home_list_lv.setOnScrollListener(this);

        //viewpager的touch事件传递给父控件
        home_container_viewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return id_viewpager.dispatchTouchEvent(event);
            }
        });

        //不拦截子view的touch 事件
        scrollView.requestDisallowInterceptTouchEvent(true);

        id_viewpager.setOffscreenPageLimit(3);
        id_viewpager.setAdapter(mAdapter = new PagerAdapter() {
            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.item_home_recommend_list, null));

                ImageView item_home_recommend_list_iv = (ImageView) view.findViewById(R.id.item_home_recommend_list_iv);
                TextView item_home_recommend_list_title_tv = (TextView) view.findViewById(R.id.item_home_recommend_list_title_tv);
                TextView item_home_recommend_list_time_tv = (TextView) view.findViewById(R.id.item_home_recommend_list_time_tv);

                item_home_recommend_list_title_tv.setText(show_lists.get(position).title);
                item_home_recommend_list_time_tv.setText(show_lists.get(position).start_time);

                GlideLoader.getInstance().get(getContext(), show_lists.get(position).picurl, item_home_recommend_list_iv, R.mipmap.home_recommend_img);

                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("id", show_lists.get(position).id).putExtra("region_id",mCityId));

                    }
                });

                container.addView(view);

                FrameLayout.LayoutParams layoutParams_ad_iv = (FrameLayout.LayoutParams) container.getLayoutParams();
                layoutParams_ad_iv.width = ScaleScreenHelperFactory.getInstance().getWidthHeight(302);
                container.setLayoutParams(layoutParams_ad_iv);

                return view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }

            @Override
            public int getCount() {
                return show_lists.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                return view == o;
            }
        });

        id_viewpager.setPageTransformer(true, new ScaleInTransformer(new AlphaPageTransformer()));




        search_title_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    closeKeybord();

//                    UtilKeyBoard.closeKeybord(search_title_et, getActivity());

                    String str = search_title_et.getText().toString().trim().replaceAll(" ", "");

                    if (TextUtils.isEmpty(str)) {

                        startActivity(new Intent(getActivity(), SearchActivity.class).putExtra("key", str));

                        return false;

                    }

                    String searchNotes = BaseApplication.BasePreferences.readSearch();

                    if (searchNotes.length() == 0) {

                        if (!searchNotes.contains(str)) {

                            String newStringNotes = str + "," + searchNotes;

                            BaseApplication.BasePreferences.saveSearch(newStringNotes);

                        }

                    } else {

                        boolean isHad = true;

                        String[] searchArray = searchNotes.split(",");

                        for (int i = 0; i < searchArray.length; i++) {

                            if (searchArray[i].contains(str)) {

                                isHad = false;

                            }

                        }

                        if (isHad) {

                            String newStringNotes = str + "," + searchNotes;

                            BaseApplication.BasePreferences.saveSearch(newStringNotes);

                        } else {

                            String StringNotes = "";

                            for (int i = 0; i < searchArray.length; i++) {

                                if (!searchArray[i].equals(str)) {

                                    StringNotes = StringNotes + "," + searchArray[i];

                                }

                            }

                            String newStringNotes = str + StringNotes + ",";

                            BaseApplication.BasePreferences.saveSearch(newStringNotes);

                        }

                    }

                    if (SearchLastFragment.is_live) {

                        try {
                            ((SearchLastFragment.RefreshSearchNotes) getAppCallBack(SearchLastFragment.class)).refresh();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    startActivity(new Intent(getActivity(), SearchActivity.class).putExtra("key", str));

                    return true;
                }
                return false;
            }
        });

        search_title_clear_ll.setVisibility(View.GONE);

        home_choose_city_ll.setOnClickListener(this);
        home_search_rl.setOnClickListener(this);
        search_title_clear_ll.setOnClickListener(this);
        // home_sign_in_ll.setOnClickListener(this);
        home_center_ad_ll.setOnClickListener(this);
//    home_integration_shop_ll.setOnClickListener(this);
        //活动
        //   home_dance_ballet_ll.setOnClickListener(this);
        //儿童亲子
        //    home_sport_ll.setOnClickListener(this);
        //演唱会
        //   home_child_ll.setOnClickListener(this);
        //惠民卡
        //   home_music_drama_ll.setOnClickListener(this);
        //话剧舞台
        //  home_manga_ll.setOnClickListener(this);

        home_title_message_rl.setOnClickListener(this);


//        setLastUpdateTime();
//
//        homeGet.user_id = BaseApplication.BasePreferences.readUserId();
//        homeGet.execute(getActivity(), false);


//        fragment_home_ll.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                Log.e("------------>", "好使么");
//
//                if (event.getAction() == MotionEvent.ACTION_MOVE) {
//
//                    Log.e("------------>", "好使么");
//                }
//
//                return true;
//            }
//        });

        home_list_lv.setFocusable(false);
        home_list_lv.setFocusableInTouchMode(false);
        home_list_lv.requestFocus();





   /*     choose_goods_num_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
        choose_goods_num_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
        choose_goods_num_nsgv.setAdapter(chooseGoodsNumGridAdapter);
*/

    /*    choose_goods_num_nsgv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));
        choose_goods_num_nsgv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(20));*/

        pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ObservableScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {

                toplists.clear();
                show_lists.clear();
                guessyoulike_lists.clear();

                views.clear();
                homeGet.user_id = BaseApplication.BasePreferences.readUserId();
                homeGet.region_id = BaseApplication.BasePreferences.getCityId();


                homeGet.execute(getActivity(), false);
               /* if (windows==null) {

                } else {

                    dia = new Dialog(getActivity(), R.style.edit_AlertDialog_style);
                    //  dia.setContentView(R.layout.activity_start_dialog);
//        dia.setContentView(MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.activity_start_dialog, null)));
                    dia.setContentView(BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.activity_start_dialog, null))));
                    mClose_btn = (ImageView) dia.findViewById(btn_close);

                    mClose_btn.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            // Toast.makeText(getActivity(), "干他妈的", Toast.LENGTH_SHORT).show();

                            if (!BaseApplication.BasePreferences.readIsLogin()) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                            } else {
                                String userid = BaseApplication.BasePreferences.readUserId();
                       *//*     String userid = BaseApplication.BasePreferences.readUserId();
                            //  String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");
                            String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");

                            Bundle bundle1 = new Bundle();

                            bundle1.putString("url",windows.url + "?id=" + userid);
                            bundle1.putString("title", windows.title);

                            startActivity(new Intent(getActivity(), IndexChainActivity.class).putExtras(bundle1));*//*
                                Intent intent = new Intent();
                                intent.putExtra("url", windows.url + "?id=" + userid);
                                intent.putExtra("title", windows.title);
                                intent.setClass(getActivity(), ChainActivity.class);
                                startActivity(intent);
                            }

                        }
                    });
                    btn_close2 = (ImageView) dia.findViewById(R.id.btn_close2);
                    btn_close2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dia.cancel();// 关闭弹出框
                        }
                    });

                    dia.show();

                    dia.setCanceledOnTouchOutside(false); // Sets whether this dialog is

                    Window w = dia.getWindow();
                    WindowManager.LayoutParams lp = w.getAttributes();
                    lp.x = 0;
                    lp.y = 40;
                    dia.onWindowAttributesChanged(lp);
                }*/


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {

            }

        });
        pullToRefreshScrollView.doPullRefreshing(true, 500);
        return view;

    }


    @Override
    public void onResume() {
        super.onResume();
        // showPopupWindow(home_ad_rl);
        try{

            setAppCallBack(new setCityNameIdCallback());
        }catch (Exception e){

        }
    }

    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        pullToRefreshScrollView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }

    public void closeKeybord() {

        UtilKeyBoard.closeKeybord(search_title_et, getActivity());
        home_search_rl.setClickable(true);
        search_title_clear_ll.setVisibility(View.GONE);
        search_title_et.setVisibility(View.GONE);
        search_title_ll.setVisibility(View.VISIBLE);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.home_choose_city_ll:

                startActivity(new Intent(getActivity(), ChooseCityActivity.class));

                break;

            case R.id.home_search_rl:

//                startActivity(new Intent(getActivity(), SearchActivity.class));

                home_search_rl.setClickable(false);
                search_title_ll.setVisibility(View.GONE);
                search_title_et.setVisibility(View.VISIBLE);
                search_title_clear_ll.setVisibility(View.VISIBLE);
                search_title_et.setFocusable(true);
                search_title_et.setFocusableInTouchMode(true);
                search_title_et.requestFocus();
                search_title_et.setText("");
                UtilKeyBoard.openKeybord(search_title_et, getActivity());

                break;

            case R.id.search_title_clear_ll:

                closeKeybord();

                break;

            //每日抽奖
/*
            case home_sign_in_ll:

                if (!BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                } else {

//                    startActivity(new Intent(getActivity(), SignInActivity.class))

                    String userid = BaseApplication.BasePreferences.readUserId();
                    String token = UtilMD5.MD5Encode(UtilMD5.MD5Encode(userid, "UTF-8") + UtilMD5.MD5Encode(Integer.parseInt(userid) % 7 + "", "UTF-8"), "UTF-8");

                    Bundle bundle1 = new Bundle();

                    bundle1.putString("url", Conn.BASE_URL + Conn.WEB_DIAL_INDEX + "?user_id=" + userid + "&token=" + token);


                    startActivity(new Intent(getActivity(), DayDaySignActivity.class).putExtras(bundle1));



                }

                break;*/

            case R.id.home_center_ad_ll:

                Bundle bundle = new Bundle();
                if (home.advertisement.get(0).type.equals("1") || home.advertisement.get(0).type.equals("3")) {
                    bundle.putString("title", home.advertisement.get(0).title);
                    bundle.putString("url", Conn.SERVICE + Conn.INDEX_BANNER_WEB + "?id=" + home.advertisement.get(0).id);

                    startActivity(new Intent(getActivity(), WebActivity.class).putExtras(bundle));
                } else if (home.advertisement.get(0).type.equals("2")) {
                    //商品详情
                    startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("id", home.advertisement.get(0).id).putExtra("region_id",mCityId));

                } else {

                }


                break;

//            case R.id.home_integration_shop_ll:
//
//                  GoodsInfoActivity
//
//                break;

            //活动

        /*    case home_dance_ballet_ll:

//                startActivity(new Intent(getActivity(), ShowActivity.class));

                startActivity(new Intent(getActivity(), ProjectActivity.class));

                break;*/
//儿童亲子
       /*     case home_sport_ll:

                Bundle bundle_child = new Bundle();
                bundle_child.putString("title", home.classify.get(0).title);
                bundle_child.putString("id", home.classify.get(0).id);

                startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_child));

                break;*/

         /*   case home_child_ll:

                Bundle bundle_show = new Bundle();
                bundle_show.putString("title", home.classify.get(1).title);
                bundle_show.putString("id", home.classify.get(1).id);

                startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_show));

                break;*/

         /*   case home_music_drama_ll:

                Bundle bundle_drama = new Bundle();
                bundle_drama.putString("title", home.classify.get(3).title);
                bundle_drama.putString("id", home.classify.get(3).id);

                startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_drama));

                break;*/
/*
            case home_manga_ll:

                Bundle bundle_coupon = new Bundle();
                bundle_coupon.putString("title", home.classify.get(2).title);
                bundle_coupon.putString("id", home.classify.get(2).id);

                startActivity(new Intent(getActivity(), ShowActivity.class).putExtras(bundle_coupon));

                break;*/

            case R.id.home_title_message_rl:

                startActivity(new Intent(getActivity(), MessageActivity.class));

                break;

        }

    }


    /*渐变效果实现代码*/
//    @Override
//    public void onScrollStateChanged(AbsListView view, int scrollState) {
//
//    }
//
//    private int mCurrentfirstVisibleItem;
//    private SparseArray recordSp = new SparseArray(0);//设置容器大小，默认是10
//    private int mIsShowTitleHeight = 400;
//
//    @Override
//    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//
//        mCurrentfirstVisibleItem = firstVisibleItem;
//
//        View firstView = view.getChildAt(0);//获取当前最顶部的item
//        if (firstView != null) {
//
//            ItemRecod itemRecord = (ItemRecod) recordSp.get(firstVisibleItem);
//
//            if (itemRecord == null) {
//                itemRecord = new ItemRecod();
//            }
//            itemRecord.height = firstView.getHeight();//获取当前最顶部Item的高度
//            itemRecord.top = firstView.getTop();//获取对应item距离顶部的距离
//            recordSp.append(firstVisibleItem, itemRecord);//添加键值对设置值
//
//            int ScrollY = getScrollY();
//            if(ScrollY <= 0){
//                title_name_tv.setVisibility(View.INVISIBLE);
//                home_ll.setBackgroundColor(Color.argb(0, 255, 255, 255));
//            }else if (ScrollY > 0 && ScrollY <= mIsShowTitleHeight) {
//                float scale = (float) ScrollY / mIsShowTitleHeight;
//                float alpha = (255 * scale);
//                title_name_tv.setVisibility(View.VISIBLE);
//                title_name_tv.setTextColor(Color.argb((int) alpha, 255, 255, 255));
//                home_ll.setBackgroundColor(Color.argb((int) alpha, 52, 147, 232));
//            } else{
//                //滑动距离大于mIsShowTitleHeight就设置为不透明
//                title_name_tv.setTextColor(Color.argb(255, 255, 255, 255));
//                home_ll.setBackgroundColor(Color.argb(255, 52, 147, 232));
//            }
//        }
//
//    }
//
//    private int getScrollY() {
//        int height = 0;
//        for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
//            ItemRecod itemRecod = (ItemRecod) recordSp.get(i);
//            if (itemRecod != null) {
//                height += itemRecod.height;
//            }
//        }
//        ItemRecod itemRecod = (ItemRecod) recordSp.get(mCurrentfirstVisibleItem);
//        if (null == itemRecod) {
//            itemRecod = new ItemRecod();
//        }
//        return height - itemRecod.top;
//    }
//
//    private class ItemRecod {
//        int height = 0;
//        int top = 0;
//    }

    public class setCityNameIdCallback implements AppCallBack {

        public void setCityNameId(String cityName, String cityId) {

            home_choose_city_tv.setText(cityName);

            mCityId = cityId;
            try{
                toplists.clear();
                show_lists.clear();
                guessyoulike_lists.clear();

                views.clear();
                homeGet.user_id = BaseApplication.BasePreferences.readUserId();
                homeGet.region_id = BaseApplication.BasePreferences.getCityId();


                homeGet.execute(getActivity(), false);
                homeListAdapter.notifyDataSetChanged();
            }catch (Exception e){

            }


        }
    }

    /**
     * 初始化需要循环的View
     * 为了灵活的使用滚动的View，所以把滚动的内容让用户自定义
     * 假如滚动的是三条或者一条，或者是其他，只需要把对应的布局，和这个方法稍微改改就可以了，
     */
    private void setView() {
        for (int i = 0; i < toplists.size(); i++) {

            final int finalI = i;

            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.item_home_ad_list, null));
            //初始化布局的控件
            TextView tv1 = (TextView) moreView.findViewById(R.id.home_ad_tv);
            //进行对控件赋值
            tv1.setText(toplists.get(finalI).title);
//            if (toplists.size() > i + 1) {
//                //因为淘宝那儿是两条数据，但是当数据是奇数时就不需要赋值第二个，所以加了一个判断，还应该把第二个布局给隐藏掉
////                tv2.setText(toplists.get(i + 1).title.toString());
//            }else {
//                moreView.findViewById(R.id.rl2).setVisibility(View.GONE);
//            }

            //添加到循环滚动数组里面去
            moreView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Bundle bundle = new Bundle();
                    bundle.putString("title", home.toplist.get(finalI).title);
                    bundle.putString("url", Conn.SERVICE + Conn.INDEX_TOPLIST_WEB + "?id=" + home.toplist.get(finalI).id);

                    Log.e("这是头条web地址", Conn.SERVICE + Conn.INDEX_TOPLIST_WEB + "?id=" + home.toplist.get(finalI).id);

                    startActivity(new Intent(getActivity(), WebActivity.class).putExtras(bundle));

                }
            });

            views.add(moreView);
        }
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//
//        isRunning=false;
//
//    }


    private void showPopupWindow(View parent) {
        if (popWindow == null) {
          /*  View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null)));*/

            View view = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.pop_select_photo2, null)));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {
        tv01 = (TextView) view.findViewById(R.id.tv_01);//拍照
        tv02 = (TextView) view.findViewById(R.id.tv_02);//相册
        tv03 = (TextView) view.findViewById(R.id.tv_03);//取消

        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
//                startCamera(ivcamera);

            }
        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
//                startAlbum(ivcamera);
            }
        });
        tv03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
            }
        });
    }


}
